package com.captainbank.tcl.tclapplication.ui.activity.basic;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.captainbank.tcl.tclapplication.R;
import com.captainbank.tcl.tclapplication.utils.Constants;
import com.captainbank.tcl.tclapplication.utils.NetworkUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.shehuan.statusview.StatusView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import cn.magicwindow.Session;

/**
 * Created by TCL on 2019/4/3.
 * Describe:
 */
public abstract class BaseActivity extends AppCompatActivity {
    private BroadcastReceiver netReceiver;
    private StatusView statusView;
    private Map<Integer, Runnable> allowablePermissionRunnables = new HashMap<>();
    private Map<Integer, Runnable> disallowablePermissionRunnables = new HashMap<>();

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 动态请求权限（Android6.0 需要添加）
     *
     * @param id                   请求授权的id 唯一标识即可
     * @param permissions          请求的权限
     * @param allowableRunnable    同意授权后的操作
     * @param disallowableRunnable 禁止权限后的操作
     */
    protected void requestPermission(int id, String[] permissions, Runnable allowableRunnable, Runnable disallowableRunnable) {
        if (allowableRunnable == null) {
            throw new IllegalArgumentException("allowableRunnable == null");
        }

        allowablePermissionRunnables.put(id, allowableRunnable);
        if (disallowableRunnable != null) {
            disallowablePermissionRunnables.put(id, disallowableRunnable);
        }

        //版本判断
        if (Build.VERSION.SDK_INT >= 23) {
            //遍历请求权限
            List<String> mPermissionList = new ArrayList<>();
            int checkCallPhonePermission;
            for (String permission : permissions) {
                //检查是否拥有权限
                checkCallPhonePermission = ContextCompat.checkSelfPermission(getApplicationContext(), permission);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permission);
                }
            }
            if (mPermissionList.isEmpty()) {
                allowableRunnable.run();
            } else {
                String[] permissionsArr = mPermissionList.toArray(new String[mPermissionList.size()]);
                //弹出对话框接收权限
                ActivityCompat.requestPermissions(BaseActivity.this, permissionsArr, id);
            }
        } else {
            allowableRunnable.run();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Runnable allowRun = allowablePermissionRunnables.get(requestCode);
                allowRun.run();
            } else {
                Runnable disallowRun = disallowablePermissionRunnables.get(requestCode);
                disallowRun.run();
            }
        } else {
            Runnable disallowRun = disallowablePermissionRunnables.get(requestCode);
            disallowRun.run();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isMultiStatusEnabled()) {
            netReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (NetworkUtil.checkNetWorkState(context) != NetworkUtil.NETWORK_NONE) {
                        showMultiStatus(Constants.MULTI_STATUS_NORMAL);
                    } else {
                        showMultiStatus(Constants.MULTI_STATUS_NONET);
                    }
                }
            };
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netReceiver, filter);
        }
        initBeforeSetContentView();
        if (isRegisterEventBus()) {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy();
        }
        if (isRegisterEventBus()) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
        }
        if (isMultiStatusEnabled()) {
            if (netReceiver != null) {
                unregisterReceiver(netReceiver);
            }
        }
    }

    /**
     * 此方法进行intent数据处理
     * 防止finish时继续执行网络请求等导致奔溃
     */
    protected void initBeforeSetContentView() {
        setContentView(getLayoutId());
        //绑定控件
        ButterKnife.bind(this);
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
        //初始化数据
        initData();
        //view与数据绑定
        initView();

        initMultiStatusView();
        //设置监听
        setListener();
    }

    protected void initData() {

    }

    protected void initView() {

    }

    protected void initMultiStatusView() {
        if (isMultiStatusEnabled()) {
            try {
                statusView = findViewById(R.id.statusView);
            } catch (Exception e) {
                statusView=null;
                e.printStackTrace();
            }
            if (statusView != null) {
                initMultiStatusLayout(statusView);
                initMultiStatusEvent(statusView);
            }
        }
    }

    //设置多状态页面布局
    protected void initMultiStatusLayout(StatusView statusView) {
        // 添加指定索引对应的状态布局
        statusView.setStatusView(Constants.MULTI_STATUS_NONET, R.layout.layout_multi_status_nonet);
        statusView.setStatusView(Constants.MULTI_STATUS_NODATA, R.layout.layout_multi_status_nodata);
        statusView.setStatusView(Constants.MULTI_STATUS_ERROR, R.layout.layout_multi_status_error);
        statusView.setStatusView(Constants.MULTI_STATUS_LOADING, R.layout.layout_multi_status_loading);
    }

    //与initMultiStatusLayout一一对应
    protected void showMultiStatus(int index) {
        if (statusView != null) {
            if (index == Constants.MULTI_STATUS_NORMAL) {
                statusView.showContentView();
            } else {
                statusView.showStatusView(index);
            }
        }
    }

    //子类重写，实现多状态布局事件，如点击重试
    protected void initMultiStatusEvent(StatusView statusView) {

    }


    //是否启用多状态（默认不启用）
    protected boolean isMultiStatusEnabled() {
        return false;
    }

    protected void setListener() {

    }

    /**
     * 子类设置布局Id
     *
     * @return the layout id
     */
    protected abstract int getLayoutId();

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.colorPrimary)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarColor(R.color.color_BLACK)
                .init();
    }

    /**
     * 是否注册EventBus
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void onPause() {
        Session.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        Session.onResume(this);
        super.onResume();
    }

}
